package com.avic.modules.equipment.rest;

import com.avic.dozer.service.IGenerator;
import com.avic.exception.BadRequestException;
import com.avic.modules.equipment.domain.Equipment;
import com.avic.modules.equipment.domain.EquipmentMaintain;
import com.avic.modules.equipment.domain.vo.ResultReturn;
import com.avic.modules.equipment.service.EquipmentMaintainService;
import com.avic.modules.equipment.service.dto.EquipmentMaintainDto;
import com.avic.modules.equipment.service.dto.EquipmentMaintainQueryCriteria;
import com.avic.modules.equipment.service.mapper.EquipmentMaintainMapper;
import com.avic.modules.log.domain.vo.LogEnumeration;
import com.avic.modules.log.domain.vo.LogVo;
import com.avic.modules.log.service.LogsService;
import com.avic.tools.config.bean.AvicConfigElement;
import com.avic.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author zhangzikang
 * @date 2022-08-14
 */
@Api(tags = "设备管理: 设备维护接口")
@RestController
@RequestMapping("/api/equipment/maintain")
@AllArgsConstructor
public class EquipmentMaintainController {

    private final IGenerator generator;
    private final EquipmentMaintainService maintainService;
    private final AvicConfigElement avicConfigElement;
    private final LogsService logsService;
    private final EquipmentMaintainMapper equipmentMaintainMapper;

    /**
     * 设备维护信息
     * @param criteria
     * @return
     */
    @ApiOperation("设备维护信息")
    @GetMapping
    @PreAuthorize("@el.check('admin','maintain:list')")
    public ResponseEntity<Object> getEquipment(EquipmentMaintainQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(maintainService.queryAll(criteria,pageable), HttpStatus.OK);
    }

    /**
     * 查看维护记录
     * @return
     */
    @ApiOperation("查看维护记录")
    @GetMapping("/list")
    public ResponseEntity<Object> getEquipMaintainList(){
        return new ResponseEntity<>(maintainService.list(), HttpStatus.OK);
    }

    /**
     * 导出设备维护信息
     * @param response
     * @param criteria
     */
    @ApiOperation("导出设备维护信息")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('admin','maintain:download')")
    public void download(HttpServletResponse response, EquipmentMaintainQueryCriteria criteria, Pageable pageable) throws IOException {

        maintainService.download(generator.convert(maintainService.queryAlls(criteria,pageable), EquipmentMaintainDto.class), response);
    }

    /**
     * 添加设备维护信息
     * @param equipment
     * @return
     */
    @ApiOperation("添加设备维护信息")
    @PostMapping
    @PreAuthorize("@el.check('admin','maintain:add')")
    public ResponseEntity<Object> addEquipment(@Validated @RequestBody EquipmentMaintain equipment){
        maintainService.addEquipment(equipment);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 修改设备维护信息
     * @param equipment
     * @return
     */
    @ApiOperation("修改设备维护信息")
    @PutMapping
    @PreAuthorize("@el.check('admin','maintain:edit')")
    public ResponseEntity<Object> editEquipment(@Validated @RequestBody EquipmentMaintain equipment){
        maintainService.editEquipment(equipment);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除设备维护信息
     * @param ids
     * @return
     */
    @ApiOperation("删除设备维护信息")
    @DeleteMapping
    @PreAuthorize("@el.check('admin','maintain:del')")
    public ResponseEntity<Object> delEquipment(@RequestBody Set<String> ids){
        List<String> strings = new ArrayList<>();
        for (String id : ids) {
            EquipmentMaintain equip = equipmentMaintainMapper.selectById(id);
            strings.add(equip.getEquipName());
        }
        // 创建操作日志
        LogVo logVo = new LogVo();
        String name = "[删除]了"+ " [" + strings.toString() + "] " +"设备维护记录信息";
        logVo.setBehavior(name);
        logVo.setAction(LogEnumeration.Delete.getMessage());
        logsService.save(logVo);
        maintainService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 上传数据采集模板图片
     *
     * @param file
     * @return
     */
    @ApiOperation("上传数据采集模板图片")
    @PostMapping("/upload")
    public ResultReturn picture(@RequestParam(value = "file") MultipartFile file) {
        ResultReturn resultVO = new ResultReturn();
        try {
            //获取文件名称
            String fileName = file.getOriginalFilename();
            // 获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if(file==null){
                throw new BadRequestException("上传文件不能为空");
            }else if(!suffixName.equalsIgnoreCase(".jpg")&&!suffixName.equalsIgnoreCase(".png")){
                throw new BadRequestException("文件格式不匹配");
            }else {
                String fileLink = "/static/TERule/" + FileUtil.uploadGeneratePath(file, avicConfigElement.getEquipTERuleLocation());
                resultVO.setState("200");
                resultVO.setMsg("请求成功");
                resultVO.setData(fileLink);
            }
            return resultVO;
        } catch (Exception e) {
            throw new BadRequestException("请求数据异常");
        }
    }
}
